package com.piece.admin.context.socket;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.ThrowableProxy;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import com.piece.core.log.support.socket.SocketLog;
import com.piece.admin.context.LogContext;
import com.piece.admin.context.LogContextHolder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class LogbackWebSocketAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {

    @Override
    protected void append(ILoggingEvent event) {
        LogContext context = LogContextHolder.get();

        Object[] argumentArray = event.getArgumentArray();
        List<Object> arguments = null == argumentArray ? Collections.emptyList() : new ArrayList<>(Arrays.asList(argumentArray));
        ThrowableProxy throwableProxy = (ThrowableProxy) event.getThrowableProxy();
        if (null != throwableProxy) {
            arguments.add(throwableProxy.getThrowable());
        }
        context.addLog(new SocketLog(event.getLevel().levelStr.toLowerCase(), event.getMessage(), arguments));
    }
}
